package com.hua.api.modules.message.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hua.api.core.constants.Status;
import com.hua.api.core.framework.redis.RedisUtils;
import com.hua.api.core.framework.util.exception.ApiError;
import com.hua.api.core.util.StringUtil;
import com.hua.api.modules.message.domain.UserMessage;
import com.hua.api.modules.message.repository.UserMessageRepository;
import com.hua.api.modules.message.service.UserMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Slf4j
@Service
@RequiredArgsConstructor
public class UserMessageServiceImpl implements UserMessageService {

    private final UserMessageRepository userMessageRepository;

    private final RedisUtils redisUtils;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void onUserMessage(JSONObject data) {
        log.info("UserMessageServiceImpl.onUserMessage data={}",data.toString());

        String context = data.getString("context");
        String title =  data.getString("title");;
        Integer needPush = data.getInteger("needPush");
        String type = data.getString("type");
        String soundPath = data.getString("soundPath");

        JSONArray array = data.getJSONArray("userIds");

        if(StringUtil.isEmptys(context,title,needPush,type,array)){
            throw ApiError.Type.LOGIC_ERROR.toException("缺少必要参数！");
        }

        for (int i=0;i<array.size();i++){
            Integer userId = array.getInteger(i);
            System.out.println("userId="+userId);
            UserMessage userMessage = new UserMessage();
            userMessage.setContext(context);
            userMessage.setTitle(title);
            userMessage.setNeedPush(needPush);
            userMessage.setType(type);
            userMessage.setCreatedTime(new Date());
            userMessage.setIsRead(Status.LOGIC_N);
            userMessage.setIsPush(Status.LOGIC_N);
            userMessage.setUserId(userId);
            userMessage.setIsSound(null==soundPath?Status.LOGIC_N:Status.LOGIC_Y);
            userMessage.setSoundPath(soundPath);
            userMessageRepository.save(userMessage);
            redisUtils.set(Status.userMessage+userId,"1",24*60*60);
        }

    }


}